<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>WebGL - 2D Rectangle Translate</title>
    <link type="text/css" href="../resources/webgl-tutorials.css" rel="stylesheet" />
    <style>
        #ui {
            width: 200px;
        }
    </style>
</head>

<body>
    <div id="info">
        <a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-2d-translation.html" target="_blank">WebGL
            二维平移</a>
        <div class="description">
            Drag sliders to translate.
        </div>
    </div>
    <canvas id="canvas"></canvas>
    <div id="uiContainer">
        <div id="ui">
            <div id="x"></div>
            <div id="y"></div>
        </div>
    </div>
</body>
<!-- vertex shader -->
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

uniform vec2 u_resolution;

void main() {
   // convert the rectangle points from pixels to 0.0 to 1.0
   vec2 zeroToOne = a_position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
</script>
<!-- fragment shader -->
<script id="2d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform vec4 u_color;

void main() {
   gl_FragColor = u_color;
}
</script>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="../resources/webgl-utils.js"></script>
<script src="../resources/webgl-lessons-ui.js"></script>
<script>
    "use strict";

    function main() {
        // 获取WebGL上下文
        /** @type {HTMLCanvasElement} */
        var canvas = document.getElementById("canvas");
        var gl = canvas.getContext("webgl");
        if (!gl) {
            return;
        }

        // 创建着色器程序
        var program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);

        // 获取顶点数据
        var positionLocation = gl.getAttribLocation(program, "a_position");

        // lookup uniforms
        var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
        var colorLocation = gl.getUniformLocation(program, "u_color");

        // Create a buffer to put positions in
        var positionBuffer = gl.createBuffer();

        // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

        var translation = [0, 0];
        var width = 100;
        var height = 30;
        var color = [Math.random(), Math.random(), Math.random(), 1];

        drawScene();

        // Setup a ui.
        webglLessonsUI.setupSlider("#x", { slide: updatePosition(0), max: gl.canvas.width });
        webglLessonsUI.setupSlider("#y", { slide: updatePosition(1), max: gl.canvas.height });

        function updatePosition(index) {
            return function (event, ui) {
                translation[index] = ui.value;
                drawScene();
            };
        }

        // 绘制场景
        function drawScene() {
            webglUtils.resizeCanvasToDisplaySize(gl.canvas);

            // 告诉WebGL如何从裁剪空间对应到像素
            gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

            // 清空画布
            gl.clear(gl.COLOR_BUFFER_BIT);

            // 使用我们的程序
            gl.useProgram(program);

            // 启用属性
            gl.enableVertexAttribArray(positionLocation);

            // 绑定位置缓冲
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

            // 设置矩形参数
            setRectangle(gl, translation[0], translation[1], width, height);

            // 告诉属性怎么从positionBuffer中读取数据 (ARRAY_BUFFER)
            var size = 2;          // 每次迭代运行提取两个单位数据
            var type = gl.FLOAT;   // 每个单位的数据类型是32位浮点型
            var normalize = false; // 不需要归一化数据
            var stride = 0;        // 0 = 移动单位数量 * 每个单位占用内存（sizeof(type)）
            var offset = 0;        // 从缓冲起始位置开始读取
            gl.vertexAttribPointer(
                positionLocation, size, type, normalize, stride, offset);

            // 设置分辨率
            gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);

            // 设置颜色
            gl.uniform4fv(colorLocation, color);

            // 绘制矩形
            var primitiveType = gl.TRIANGLES;
            var offset = 0;
            var count = 6;
            gl.drawArrays(primitiveType, offset, count);
        }
    }

    // Fill the buffer with the values that define a rectangle.
    function setRectangle(gl, x, y, width, height) {
        var x1 = x;
        var x2 = x + width;
        var y1 = y;
        var y2 = y + height;
        gl.bufferData(
            gl.ARRAY_BUFFER,
            new Float32Array([
                x1, y1,
                x2, y1,
                x1, y2,
                x1, y2,
                x2, y1,
                x2, y2,
            ]),
            gl.STATIC_DRAW);
    }

    main();
</script>

</html>